from django.contrib.auth.backends import ModelBackend
import re

from .models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """重写认证后返回的响应体"""
    return {
        "token": token,
        "username": user.username,
        "user_id": user.id,
    }


def get_user_by_count(username):
    """根据传入的参数查询用户对象"""
    try:
        if re.match(r'1[3-9]{9}', username):
            # 手机号登陆
            user = User.objects.get(mobile=username)
        else:
            # 用户名登陆
            user = User.objects.get(username=username)
    except User.DoesNotExist:
        return None
    # 如果没有异常
    else:
        return user


class UsernameMobileBackend(ModelBackend):
    """实现多账号登登录的,重写django的后端"""
    """
    重写认证方式,使用多账号登录
    :param request:   本次登录请求对象
    :param username: 用户名/手机号
    :param password: 密码
    :return: 要么返回查到的user/None
    """

    def authenticate(self, request, username=None, password=None, **kwargs):
        """重写authenticate方法,实现多账号登录"""

        # 调用方法,获取用户对象
        user = get_user_by_count(username)

        # 校验user是否存在并校验密码是否正确
        if user and user.check_password(password):
            return user

# def jwt_response_payload_handler(token, user=None, request=None):
#     """重写jwt登录认证方法的响应体"""
#     return {
#         'token': token,
#         "username":user.username,
#         "user_id":user.id,
#     }
#
# def get_user_count(count):
#     """根据传入的信息查询用户信息"""
#     try:
#         if re.match(r'1[3-9]\d{9}', count):
#             # 手机号登录
#             user = User.objects.get(mobile=count)
#         else:
#             # 用户名登录
#             user = User.objects.get(username=count)
#     except User.DoesNotExist:
#         return None
#     # 如果用户存在,则返回
#     else:
#         return user
#
#
# class UsernameMobileBackend(ModelBackend):
#     """修改用户系统后端,实现多账号登录"""
#
#     def authenticate(self, request, username=None, password=None, **kwargs):
#         # 获取参数 username, mobile
#
#         # 根据传⼊的username获取user对象,username可以是⼿机号也可以是账号
#         user = get_user_count(username)
#
#         # 校验user是否存在并校验密码是否正确
#         if user and user.check_password(password):
#             return user
